#!/bin/bash

#p1=`echo $1 | cut -d. -f2`
#p2=`echo $2 | cut -d. -f2`


#create a trimmed file , add labels too

RESULT_DIR="."
LINES=${1-500000}

# trimming to 0.5M because matlab sucks

echo "trimming first $LINES lines"

function trim {
 # $1 target_file
 # $2 source_file
 # $3 predictor_label
 trm_f=$1
 rm $trm_f 2>/dev/null #hides error output
 printf "cycle\t%s\t%s_missed\t%s_total\t%s_unique\n" $3 $3 $3 $3 >> $1
 head -n $LINES $RESULT_DIR/$2  >> $1
}

function trimall {
 # $1 pattern either "conditional" or "indirect" , please
 for i in `ls $RESULT_DIR/$1.* | cut -d/ -f2 | sort | uniq`
	do
	n=`echo $i | cut -d. -f2`
	trim trimm_$i $i $n
	echo "trimmed: $i > trimm_$i [predictor: $n]"
	#break
	done
}

function mergeall { # $1 either "ind" or "cond" , please
  for test_set in `ls trimm_$1* | cut -d. -f3 | sort | uniq`
	do
	echo $test_set
	RESULT="results.$1.$test_set.csv"
	echo "building $RESULT"	
	rm $RESULT 2>/dev/null #ignore error
	for res in `ls trimm_$1.*.$test_set.csv | sort | uniq`
		do
		if [ ! -f $RESULT ];
		then
			cp $res $RESULT
			echo "start: $res"
			continue
		fi
		join -t $'\t' $RESULT $res > tmp
		rm $RESULT		
		cp tmp $RESULT
		rm tmp
		echo "joined: $res"
		done
	done
}

function mergetraces { #$1 either 'indirect_trace' or 'conditional_trace'
  for test_set in `ls $1.* | cut -d. -f3 | sort | uniq`
	do
	echo $test_set
	RESULT="results.$1.$test_set.csv"
	echo "building $RESULT"	
	rm $RESULT 2>/dev/null #ignore error
	for res in `ls trimm_$1.*.$test_set.csv | sort | uniq`
		do
		predictor=`echo $res | cut -d. -f2`
		#echo "$res $predictor"
		if [ ! -f $RESULT ];
		then
			echo "source: $res"
			printf "cycle\tbranch\tcontext\ttarget\treal\t%s\t%s_cor\n" $predictor $predictor >> $RESULT
			cut -f1,2,3,4,5,6,7 $res >> $RESULT
		continue
		fi
		printf "cycle\t%s\t%s_cor\n" $predictor $predictor > tmp_cut
		cut -f1,6,7 $res >> tmp_cut
		join -t $'\t' $RESULT tmp_cut > tmp
		mv tmp $RESULT
		rm tmp_cut
		echo "concated: $res"
		done
	done
}

function trimtraces {
 # $1 pattern either "conditional" or "indirect" , please
 for i in `ls $RESULT_DIR/$1.* | cut -d/ -f2 | sort | uniq`
	do
 	head -n $LINES $RESULT_DIR/$i  > trimm_$i
	echo "trimmed: $i > trimm_$i [predictor: $n]"
	#break
	done
}


cd results

#trimall "indirect_count"
#mergeall "indirect_count"

trimall "conditional_count"
mergeall "conditional_count"

trimtraces "conditional_trace"
mergetraces "conditional_trace"
#mergetraces "indirect_trace"


